package manage.controller;

import manage.dao.UserMapper;
import manage.model.Contract;
import manage.model.User;
import manage.service.impl.ContractServiceImpl;
import manage.util.LogUtil;
import manage.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
public class ContractController {
    @Autowired
    private ContractServiceImpl contractService;
    @Autowired
    private UserMapper userMapper;

    private  User user;
    //返回contract的list
    @RequestMapping(value = "/contract")
    @ResponseBody
    public Msg contractData(HttpServletRequest request, Authentication authentication){
        String page = request.getParameter("currentPage");
        String limit = request.getParameter("pageSize");
        UserDetails userDetails =(UserDetails) authentication.getPrincipal();
        user = userMapper.selectByPrimaryKey(userDetails.getUsername());
        return Msg.success().add("data",contractService.selectAll(page,limit));
    }

    //添加contract
    @ResponseBody
    @RequestMapping(value = "/addContract",method = RequestMethod.POST)
    public Msg addContract(Contract contract){

        contract.setOperatorId(user.getAccount());
        contract.setOperatDate(new Date());
        String s= contractService.insert(contract);
        LogUtil.writeFileLog(user.getAccount(),"添加合同:"+contract.toString());
        return Msg.attendanceAdd(s);
    }

    //修改contract
    @ResponseBody
    @RequestMapping(value = "/addContract",method = RequestMethod.PUT)
    public Msg updateContract(Contract contract){

        contract.setOperatDate(new Date());
        contract.setOperatorId(user.getAccount());
        String s= contractService.update(contract);
        LogUtil.writeFileLog(user.getAccount(),"修改合同-改:"+contract.toString());
        return Msg.attendanceAdd(s);
    }
    //删除contract
    @ResponseBody
    @RequestMapping("/delContract")
    public Msg delContract(@RequestBody Integer id){
        String s = contractService.del(id);
        LogUtil.writeFileLog(user.getAccount(),"删除合同:"+id.toString());
        return Msg.attendanceAdd(s);
    }

    //根据主键查contract 和修改配合使用
    @ResponseBody
    @RequestMapping("/contractSelect")
    public Msg selContract(@RequestBody Integer id){
        Contract contract = contractService.select(id);
        LogUtil.writeFileLog(user.getAccount(),"修改合同-查:"+contract.toString());
        return Msg.success().add("contract",contract);
    }
}
